package conterlles

import (
	"day12_10_homework/models/mysql"
	"day12_10_homework/models/redis"
	"day12_10_homework/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

func UserLogin(c *gin.Context) {
	tel := c.PostForm("tel")
	sendSmsCode := c.PostForm("sendSmsCode")
	num := "sendSms_login" + tel
	get := redis.Rdb.Get(redis.Ctx, num)
	if get.Val() == "" {
		c.JSON(http.StatusOK, JsonRes{
			Code:    500,
			Message: "暂未获取验证码",
			Data:    nil,
		})
		return
	}
	if get.Val() != sendSmsCode {
		c.JSON(http.StatusOK, JsonRes{
			Code:    500,
			Message: "验证码错误",
			Data:    nil,
		})
		return
	}
	password := c.PostForm("password")
	if tel == "" || password == "" {
		c.JSON(http.StatusOK, JsonRes{
			Code:    500,
			Message: "不能为空",
			Data:    nil,
		})
		return
	}
	if !pkg.Tel(tel) {
		c.JSON(http.StatusOK, JsonRes{
			Code:    500,
			Message: "手机号格式错误",
			Data:    nil,
		})
		return
	}
	password1 := password + "1234"
	password2 := pkg.Md5(password1)
	user, err := mysql.Login(tel)
	if err != nil {
		c.JSON(http.StatusOK, JsonRes{
			Code:    500,
			Message: "登录失败",
			Data:    nil,
		})
		return
	}
	if user.ID == 0 {
		c.JSON(http.StatusOK, JsonRes{
			Code:    500,
			Message: "登录失败",
			Data:    nil,
		})
		return
	}
	if password2 != user.Password {
		c.JSON(http.StatusOK, JsonRes{
			Code:    500,
			Message: "登录失败",
			Data:    nil,
		})
		return
	}
	redis.Rdb.Del(redis.Ctx, num)
	handler, _ := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	c.JSON(http.StatusOK, JsonRes{
		Code:    200,
		Message: "登录成功",
		Data:    handler,
	})
}
